package com.ruoyi.socket.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.bussiness.domain.TContractCoin;
import com.ruoyi.bussiness.domain.TCurrencySymbol;
import com.ruoyi.bussiness.domain.TSecondCoinConfig;
import com.ruoyi.bussiness.service.ITContractCoinService;
import com.ruoyi.bussiness.service.ITCurrencySymbolService;
import com.ruoyi.bussiness.service.ITSecondCoinConfigService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.socket.manager.WebSocketUserManager;
import com.ruoyi.util.Kline;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.*;

@Slf4j
@Component
public class MarketThreadStock {
    @Resource
    private ITSecondCoinConfigService secondCoinConfigService;
    @Resource
    private ITContractCoinService contractCoinService;
    @Resource
    private ITCurrencySymbolService tCurrencySymbolService;
    @Resource
    private WebSocketUserManager webSocketUserManager;

    private static final Set<String> strings = new HashSet<>();
    @Scheduled(fixedRate = 1000 * 60 * 60 * 24)
    public void getSecondCoins() {
        LocalDate today = LocalDate.now();
        DayOfWeek dayOfWeek = today.getDayOfWeek();

        //秒合约
        TSecondCoinConfig tSecondCoinConfig = new TSecondCoinConfig();
        tSecondCoinConfig.setMarket("meigu");
        tSecondCoinConfig.setStatus(1L);
        List<TSecondCoinConfig> tSecondCoinConfigs = secondCoinConfigService.selectTSecondCoinConfigList(tSecondCoinConfig);
        for (TSecondCoinConfig secondCoinConfig : tSecondCoinConfigs) {
//            strings.add(secondCoinConfig.getCoin().toUpperCase());
            strings.add(secondCoinConfig.getCoin());
//            strings.add(secondCoinConfig.getCoin());
        }
        //U本位
        TContractCoin tContractCoin =new TContractCoin();
        tContractCoin.setEnable(0L);
        tContractCoin.setMarket("meigu");
        List<TContractCoin> tContractCoins = contractCoinService.selectTContractCoinList(tContractCoin);
        for (TContractCoin contractCoin : tContractCoins) {
            strings.add(contractCoin.getCoin());
        }
        //币币
        TCurrencySymbol tCurrencySymbol = new TCurrencySymbol();
        tCurrencySymbol.setEnable("1");
        tCurrencySymbol.setMarket("meigu");
        List<TCurrencySymbol> tCurrencySymbols = tCurrencySymbolService.selectTCurrencySymbolList(tCurrencySymbol);
        for (TCurrencySymbol currencySymbol : tCurrencySymbols) {
            strings.add(currencySymbol.getCoin());
        }
    }
    @Async
//    @Scheduled(cron = "*/9 * * * * ?", initialDelay = 500)
    @Scheduled(fixedRate = 9000, initialDelay = 500)
    public void marketThreadRun() throws URISyntaxException {
        List<Kline> list = new ArrayList<>();
        for (String string : strings) {
            Kline kline = new Kline();
            kline.setCode(string);
            kline.setKline_timestamp_end("0");
            kline.setAdjust_type("0");
            kline.setKline_type("1");
            kline.setQuery_kline_num("1");
            list.add(kline);
        }
        String list_data = JSONArray.toJSONString(list);
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
//                     Random random = new Random();
//                     double v = random.nextDouble();
//                     String url = "";
//                     url = "https://api-q.fx678img.com/getQuote.php?exchName=WGJS&symbol="+string.toUpperCase()+"&st="+v;
//                         String result = HttpRequest.get(url)
//                                 .header("referer", "https://quote.fx678.com/")
//                                 .header("Host","api-q.fx678img.com")
//                                 .header("Origin","https://quote.fx678.com")
//                                 .timeout(20000)
//                                 .execute().body();
//                    webSocketUserManager.metalKlineSendMeg(result,string);
//                    webSocketUserManager.metalDETAILSendMeg(result,string);
                String token = "bceaf65c459d7956334bf872c900d8b7-c-app";//alltick token
                try {
                    HashMap<String, List<String>> data = getTickData(token, list_data);

                } catch (Exception e) {
                    log.error("123{}", e.getMessage());
                }
            }
        });
        thread.start();

    }
    /**
     * 各种开发对接 @xxccmake
     * https://t.me/xxccmake
     */
    private  HashMap<String, List<String>> getTickData(String token, String list_data) {
        String trace = UUID.randomUUID().toString();
        String query = "{\"trace\" : \"" + trace + "\",\"data\" : {\"data_list\" :" + list_data + "}}";
        String url = String.format("https://quote.alltick.io/quote-stock-b-api/batch-kline?token=%s", token);
//        log.error(url);
//        String result = HttpRequest.get(url)
//                .header("Accept", "application/json, text/javascript, */*; q=0.01")
//                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0")
//                .timeout(5000)
//                .execute().body();

//        System.out.println(result);
        String result = sendPost(url,query);// 可用 Hutool、OkHttp


        HashMap<String, List<String>> map1 = new HashMap<>();

        if (StringUtils.isNotEmpty(result) && result.contains("kline_list")) {
            JSONObject resultObject = JSONObject.parseObject(result);
            if (!resultObject.get("ret").toString().equals("200")) {
                return null;
            }

            JSONObject data = resultObject.getJSONObject("data");
            JSONArray kline_list = data.getJSONArray("kline_list");
            if (!kline_list.isEmpty() || kline_list.size() > 0) {

                for (int i = 0; i < kline_list.size(); i++) {
                    HashMap<String, List<String>> map = new HashMap<>();
                    List<String> t = new ArrayList<>();
                    List<String> c = new ArrayList<>();
                    List<String> o = new ArrayList<>();
                    List<String> h = new ArrayList<>();
                    List<String> l = new ArrayList<>();
                    List<String> v = new ArrayList<>();
                    List<String> code = new ArrayList<>();

                    JSONObject kline = kline_list.getJSONObject(i);
                    JSONArray da = kline.getJSONArray("kline_data");
                    JSONObject kline_data = da.getJSONObject(0);

                    code.add(kline.getString("code").toString());
                    t.add(kline_data.getString("timestamp").toString());
                    c.add(kline_data.getString("close_price").toString());
                    o.add(kline_data.getString("open_price").toString());
                    h.add(kline_data.getString("high_price").toString());
                    l.add(kline_data.getString("low_price").toString());
                    v.add(kline_data.getString("volume").toString());

                    map.put("code", code);
                    map.put("t", t);
                    map.put("c", c);
                    map.put("o", o);
                    map.put("h", h);
                    map.put("l", l);
                    map.put("v", v);

                    if (null != map && map.containsKey("t")) {
                        String result_data = JSONObject.toJSONString(map);
                        webSocketUserManager.metalKlineSendMeg(result_data,code.get(0).toLowerCase());
                        webSocketUserManager.metalDETAILSendMeg(result_data,code.get(0).toLowerCase());
                    }
                }
            }
        } else {
            log.info("java: MarketThreadMetal.java url: {} result: {}", url, result);
        }
//        System.out.println(JSONObject.toJSONString(map));
        return map1;
    }

    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}
